import axios from "axios"
import { useBaseStore } from "/@/store/base/baseStore"
import { openMessage, openModal } from "/@/utils/tool"

const service = axios.create({
	timeout: 50000,
})

/**
 * 异常处理拦截器
 * 
 * @param {*} error
 */
const errorHandler = (error) => {
	// 判断是否是响应错误信息
	if (error.response) {
		if (error.response.status == 401) {
			location.reload();
		} else if (error.response.status == 403) {
			openMessage("没有权限！", "error");
		} else {
			openMessage("网络异常，请稍候再试！", "error");
		}
	}
	return Promise.reject(error);
};

// 请求拦截器
service.interceptors.request.use(
	config => {
		const baseStore = useBaseStore()
		const userInfo = baseStore.handleGetUserInfo
		// 在发送请求之前做些什么
		config.headers.token = userInfo.token
		config.headers.teamid = userInfo.now_team_id
		config.headers.role = userInfo.role
		config.headers.devicetype = "pc"
		// ...
		return config
	},
	errorHandler
)


// 响应拦截器
service.interceptors.response.use(
	response => {
		const res = response.data
		switch (res.code) {
			case 1:
				return res;
				break;
			case 4001:
			case 4002:
				openModal(
					{ title: "温馨提示", content: "当前登录过期，请重新登录" },
					() => {
					}
				);
				return Promise.reject(res);
				break;
			case 12:
				openModal(
					{ title: "权限不足", content: "权限不足，请联系管理员" },
					() => {
					}
				);
				return Promise.reject(res);
				break;
			default:
				openMessage(res?.msg || res?.message || "网络异常，请稍候再试！", "error");
				return Promise.reject(res);
				break;
		}
	},
	errorHandler
)
export const request = (options) => {
	options.method = options.method || "GET";
	options.headers = {
		...options.headers,
		"Content-Type": "application/json",
	};
	if (
		options.method.toLowerCase() === "get" ||
		options.method.toLowerCase() === "delete"
	) {
		options.params = options.params;
	} else if (
		options.method.toLowerCase() === "post" ||
		options.method.toLowerCase() === "put"
	) {
		options.data = options.data;
	}
	return service(options)
}